package com.freewater.javabase.demo.crypto;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AES对称加密算法：CBC模式，它需要一个随机数作为IV参数，这样对于同一份明文，每次生成的密文都不同。
 * 密钥长度是固定的128/192/256位。
 */
public class AesCbcCrypto {
    public static void main(String[] args) {
        try {
            // 原文:
            String message = "Hello, world!";
            System.out.println("Message: " + message);
            // 256位密钥 = 32 bytes Key:
            byte[] key = "1234567890abcdef1234567890abcdef".getBytes(StandardCharsets.UTF_8);
            byte[] input = message.getBytes(StandardCharsets.UTF_8);
            byte[] encrypt = encrypt(key, input);
            System.out.println("Encrypted: " + Base64.getEncoder().encodeToString(encrypt));

            byte[] decrypt = decrypt(key, encrypt);
            System.out.println("Decrypted: " + new String(decrypt, StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 密钥长度是固定的128/192/256位
    public static byte[] encrypt(byte[] key, byte[] input) throws InvalidAlgorithmParameterException, InvalidKeyException,
            NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        SecureRandom secureRandom = new SecureRandom();
        byte[] iv = secureRandom.generateSeed(16);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] bytes = cipher.doFinal(input);
        return join(iv, bytes);
    }

    // 密钥长度是固定的128/192/256位
    public static byte[] decrypt(byte[] key, byte[] input) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = new byte[16];
        byte[] data = new byte[input.length - 16];
        System.arraycopy(input, 0, iv, 0, 16);
        System.arraycopy(input, 16, data, 0, data.length);
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] bytes = cipher.doFinal(data);
        return bytes;
    }

    public static byte[] join(byte[] bt1, byte[] bt2) {
        byte[] result = new byte[bt1.length + bt2.length];
        System.arraycopy(bt1, 0, result, 0, bt1.length);
        System.arraycopy(bt2, 0, result, bt1.length, bt2.length);
        return result;
    }
}
